package com.pms.web;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.pms.controller.BaseController;
import com.pms.entity.*;
import com.pms.exception.R;
import com.pms.exception.RRException;
import com.pms.rpc.GetWayRpcService;
import com.pms.rpc.SystemRpcService;
import com.pms.service.IGroupIotAgencyService;
import com.pms.service.IIotAgencyService;
import com.pms.service.IIotWaterPumpGroupService;
import com.pms.service.tsdb.IIotDeviceService;
import com.pms.util.idutil.SnowFlake;
import com.pms.validator.Assert;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.math.BigDecimal;
import java.util.*;
/**
 * <p>
 * 二供模块 机构管理 接口 前端控制器
 * 机构级别:{1-系统,2-物业/公司,3-小区,4-水泵房,5-水泵组}
 * </p>
 * @author asus
 * @since 2018-07-17
 */
@RestController
@RequestMapping("/iot/agencyManage")
@Api(value="二供模块 机构管理 接口" ,description = "二供模块 机构管理 接口")
public class IotAgencyController extends BaseController {
    @Autowired
    GetWayRpcService getWayRpcService;
    @Autowired
    SystemRpcService systemRpcService;
    @Autowired
    IIotAgencyService orgService;
    @Autowired
    IIotWaterPumpGroupService waterPumpGroupService;
    @Autowired
    IGroupIotAgencyService groupIotAgencyService;
    @Autowired
    IIotDeviceService iotDeviceService;

    /**
     * 添加
     * @param
     * @return
     */
    @ApiOperation(value = "添加(物业/小区/水泵房/水泵组)接口")
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="parentLevel",value="上级机构级别(1-添加物业,2-添加小区,3-添加水泵房,4-添加水泵组)",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="parentId",value="上级机构id",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="name",value="名称",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="code",value="编码",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="linkName",value="负责人名称",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="linkPhone",value="负责人电话",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="desc",value="简介",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="agencyAddress",value="地址",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="longitude",value="经度",required = false,dataType = "Double",paramType="form"),
            @ApiImplicitParam(name="latitude",value="纬度",required = false,dataType = "Double",paramType="form"),
            @ApiImplicitParam(name="dataType",value="水泵组数据传输方式(1-有线网络,2-移动流量)",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="groupPhone",value="水泵组设备手机号",required = false,dataType = "String",paramType="form"),
    })
    public R add(String desc,String linkPhone,String linkName, String code, Long parentId, String name
            ,String agencyAddress,Double longitude,Double latitude,Integer parentLevel,Integer dataType,String groupPhone){
        Assert.isNull(parentId,"上级机构不能为空");
        Assert.isNull(parentLevel,"上级机构级别不能为空");
        Assert.isBlank(name,"名称不能为空");
        Assert.isExcessLength(name,20,"名称内容过长");
        if(StringUtils.isNotBlank(desc)){
            Assert.isExcessLength(desc,200,"简介内容过长");
        }
        if(StringUtils.isNotBlank(agencyAddress)){
            Assert.isExcessLength(agencyAddress,50,"地址内容过长");
        }
        if(parentLevel<1||parentLevel>4){return R.error(400,"上级机构级别参数错误");}
        if(parentLevel!=4){//添加 水泵房时 编码自动生成, 不需要 负责人名称，负责人电话
            Assert.isBlank(code,"编码不能为空");
            Assert.isExcessLength(code,20,"编码内容过长");
            Assert.isBlank(linkName,"负责人名称不能为空");
            Assert.isExcessLength(linkName,20,"负责人名称过长");
            Assert.isBlank(linkPhone,"负责人电话不能为空");
            Assert.isExcessLength(linkPhone,20,"负责人电话过长");
        }
        Map<String,String> currentUserMap = getCurrentUserMap();
        UserInfo currentUserInfo=systemRpcService.getUserByUsername(currentUserMap.get("userName"),currentUserMap.get("companyCode"));
        Assert.isNull(currentUserInfo.getId(),"请重新登录");

        IotAgency paraentAgency =null;
        if(parentLevel==1){
            if(parentId.longValue() != -1L){
                return R.error(400,"上级机构参数信息有误");
            }
            paraentAgency = new IotAgency();
            paraentAgency.setId(-1L);
            paraentAgency.setName("系统");
            paraentAgency.setLevel(1);//设为1级分区级别
        }else{
            paraentAgency =orgService.selectById(parentId);
            Assert.isNull(paraentAgency,"未查询到上级机构信息");
            if(paraentAgency.getLevel()!= parentLevel){
                return R.error(400,"上级机构参数信息有误");
            }
        }
        // 添加物业/公司，小区，水泵房
        if(parentLevel < 4){
            if(parentLevel<3){// 添加 物业/小区，名称全局唯一
                if(orgService.selectCount(new EntityWrapper<IotAgency>().eq("company_code",currentUserMap.get("companyCode")).eq("agency_name",name))>0){
                    return R.error(400,"已存在相同名称");
                }
            }
            if(parentLevel== 3){// 添加水泵房，水泵房名称同层级唯一
                if(orgService.selectCount(new EntityWrapper<IotAgency>().eq("company_code",currentUserMap.get("companyCode")).eq("parent_id",parentId).eq("agency_name",name))>0){
                    return R.error(400,"已存在相同名称");
                }
            }
            // 编码全局唯一
            if(orgService.selectCount(new EntityWrapper<IotAgency>().eq("company_code",currentUserMap.get("companyCode")).eq("agency_code",code))>0){
                return R.error(400,"已存在相同编码");
            }
            if(paraentAgency.getLevel()>1){// 判断当前添加 小区/水泵房 ，需选择定位 经纬度
                if(longitude == null || latitude==null ){
                    return R.error(400,"请定位经纬度");
                }
            }
            IotAgency insertAgency = new IotAgency();
            insertAgency.setId(BaseModel.returnStaticIdLong());
            insertAgency.setName(name);
            insertAgency.setCode(code);
            insertAgency.setLinkName(linkName);
            insertAgency.setLinkPhone(linkPhone);
            insertAgency.setDesc(desc);
            insertAgency.setLongitude(longitude);
            insertAgency.setLatitude(latitude);
            insertAgency.setAgencyAddress(agencyAddress);
            insertAgency.setStatus(1);
            insertAgency.setParentId( paraentAgency.getId() );
            insertAgency.setParentName(paraentAgency.getName());
            insertAgency.setLevel(paraentAgency.getLevel()+1);// 设置机构级别加1
            insertAgency.setCompanyCode(currentUserInfo.getCompanyCode());
            insertAgency.setCreateTime(new Date());
            insertAgency.setUpdateTime(insertAgency.getCreateTime());
            insertAgency.setCreateBy(currentUserInfo.getId());
            insertAgency.setUpdateBy(currentUserInfo.getId());
            orgService.insert(insertAgency);
        }
        // 添加 水泵组设备
        if(parentLevel == 4){
            Assert.isNull(dataType,"请选择数据传输方式");
            if(dataType!=2){dataType=1;}// 默认为有线网络传输
            if(dataType==2){
                Assert.isNull(groupPhone,"请填写设备手机号");
               if(waterPumpGroupService.selectCount(new EntityWrapper<IotWaterPumpGroup>().eq("company_code",currentUserMap.get("companyCode")).eq("group_phone",groupPhone))>0){
                    return R.error(400,"已存在相同设备手机号");
               }
            }
            if(waterPumpGroupService.selectCount(new EntityWrapper<IotWaterPumpGroup>().eq("company_code",currentUserMap.get("companyCode")).eq("house_id",parentId).eq("group_name",name))>0){
                return R.error(400,"已存在相同名称");
            }
            IotWaterPumpGroup insertWaterPumpGroup = new IotWaterPumpGroup();
            Long id= BaseModel.returnStaticIdLong();
            insertWaterPumpGroup.setId(id);
            insertWaterPumpGroup.setName(name);
            insertWaterPumpGroup.setCode("wp_"+insertWaterPumpGroup.getId());// 设置编号
            insertWaterPumpGroup.setLinkName(linkName);
            insertWaterPumpGroup.setLinkPhone(linkPhone);
            insertWaterPumpGroup.setParentId( paraentAgency.getId() );
            insertWaterPumpGroup.setParentName(paraentAgency.getName());
            insertWaterPumpGroup.setCommunityId(paraentAgency.getParentId());
            insertWaterPumpGroup.setCommunityName(paraentAgency.getParentName());
            insertWaterPumpGroup.setDataType(dataType);
            insertWaterPumpGroup.setGroupPhone(groupPhone);
            insertWaterPumpGroup.setDataSource(1);// 默认数据来源为系统
            insertWaterPumpGroup.setDesc(desc);
            insertWaterPumpGroup.setCreateTime(new Date());
            insertWaterPumpGroup.setCompanyCode(currentUserInfo.getCompanyCode());
            insertWaterPumpGroup.setCreateTime(new Date());
            insertWaterPumpGroup.setUpdateTime(insertWaterPumpGroup.getCreateTime());
            insertWaterPumpGroup.setCreateBy(currentUserInfo.getId());
            insertWaterPumpGroup.setUpdateBy(currentUserInfo.getId());
            if (insertWaterPumpGroup.getDataType()==2){
                //插入数据卡充值记录
                IotCardRecharge cardRecharge=new IotCardRecharge();
                Long cardId= BaseModel.returnStaticIdLong();
                cardRecharge.setCardId(cardId);
                cardRecharge.setGroupId(id);
                cardRecharge.setTotalAmount(new BigDecimal(0));//总金额
                cardRecharge.setCurrentBalance(new BigDecimal(0));//当前余额
                cardRecharge.setRecentlyCurrentBalance(new BigDecimal(0));//最近充值金额
                cardRecharge.setRecentlyData(null);//最近充值时间
                cardRecharge.setRecentlyName(null);//最近充值人
                cardRecharge.setGroupName(name);//设备名称
                cardRecharge.setPhone(groupPhone);//手机卡号
                cardRecharge.setState(1);
                cardRecharge.setMonthlyFeeStandard(new BigDecimal(0));//每月消费标准
                cardRecharge.setCrtTime(new Date());
                cardRecharge.setCrtUser(currentUserInfo.getName());
                waterPumpGroupService.insert_insertWaterPumpGroup_cardRecharge(insertWaterPumpGroup,cardRecharge);
            }else{
                waterPumpGroupService.insert(insertWaterPumpGroup);
            }
            //添加设备组时 同步添加 百度物接入 iot配置
            iotDeviceService.createWaterPumpConfig(null,insertWaterPumpGroup.getCode());
        }
        return R.ok();
    }
    /*
     * 修改信息
     * @param
     * @return
     */
    @ApiOperation(value = "修改信息")
    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="id",value="机构id",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="level",value="级别(2-物业/公司,3-小区,4-水泵房,5-水泵组)",required = true,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="name",value="名称",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="code",value="编码",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="linkName",value="负责人名称",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="linkPhone",value="负责人电话",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="desc",value="简介",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="agencyAddress",value="地址",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="longitude",value="经度",required = false,dataType = "Double",paramType="form"),
            @ApiImplicitParam(name="latitude",value="纬度",required = false,dataType = "Double",paramType="form"),
            @ApiImplicitParam(name="dataType",value="水泵组数据传输方式(1-有线网络,2-移动流量)",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="groupPhone",value="水泵组设备手机号",required = false,dataType = "String",paramType="form"),
    })
    public R edit(String desc,String linkPhone,String linkName, String code, Long id,Integer level, String name
            ,String agencyAddress,Double longitude,Double latitude,Integer dataType,String groupPhone){
        Assert.isNull(id,"参数id不能为空");
        Assert.isNull(level,"参数level不能为空");
        Assert.isBlank(name,"名称不能为空");
        if(StringUtils.isNotBlank(desc)) {
            Assert.isExcessLength(desc, 200, "简介内容过长");
        }
        Map<String,String> currentUserMap = getCurrentUserMap();
        Map<String,Boolean> valueMap = getWayRpcService.validateUserToken(currentUserMap);
        if(!valueMap.get("value")){
            return R.error(400,"Token失效,请重新登录");
        }
        UserInfo currentUserInfo=systemRpcService.getUserByUsername(currentUserMap.get("userName"),currentUserMap.get("companyCode"));
        Assert.isNull(currentUserInfo.getId(),"请重新登录");

        if(level>4){// 5-修改水泵组
            IotWaterPumpGroup oldWaterPumpGroup = waterPumpGroupService.selectById(id);
            Assert.isNull(oldWaterPumpGroup,"未查询到水泵组信息");
            Assert.isNull(dataType,"请选择数据传输方式");
            if(dataType!=2){dataType=1;}// 默认为有线网络传输
            if(dataType==2){
                Assert.isNull(groupPhone,"请填写设备手机号");
                if(!groupPhone.equals(oldWaterPumpGroup.getGroupPhone())) {// 判断设备手机号是否有修改
                    if (waterPumpGroupService.selectCount(new EntityWrapper<IotWaterPumpGroup>().eq("company_code",currentUserMap.get("companyCode")).eq("group_phone", groupPhone)) > 0) {
                        return R.error(400, "已存在相同设备手机号");
                    }
                }
            }
            if(!name.equals(oldWaterPumpGroup.getName())){// 判断名称是否有修改
                if(waterPumpGroupService.selectCount(new EntityWrapper<IotWaterPumpGroup>().eq("company_code",currentUserMap.get("companyCode")).eq("house_id",oldWaterPumpGroup.getParentId()).eq("group_name",name))>0){
                    return R.error(400,"已存在相同名称");
                }
            }
            oldWaterPumpGroup.setName(name);
            oldWaterPumpGroup.setGroupPhone(groupPhone);
            oldWaterPumpGroup.setDataType(dataType);
            oldWaterPumpGroup.setDesc(desc);
            // 设置修改人
            oldWaterPumpGroup.setUpdateTime(new Date());
            oldWaterPumpGroup.setUpdateBy(currentUserInfo.getId());
            waterPumpGroupService.updateById(oldWaterPumpGroup);
        }
        // 修改 2物业，3小区，4水泵房
        if(level<5){
            IotAgency oldAgency = orgService.selectById(id);
            Assert.isNull(oldAgency,"未查询到当前机构信息");
            Assert.isExcessLength(name,20,"名称内容过长");
            Assert.isBlank(code,"编码不能为空");
            Assert.isExcessLength(code,20,"编码内容过长");
            Assert.isBlank(linkName,"负责人名称不能为空");
            Assert.isExcessLength(linkName,20,"负责人名称过长");
            Assert.isBlank(linkPhone,"负责人电话不能为空");
            Assert.isExcessLength(linkPhone,20,"负责人电话过长");
            if (StringUtils.isNotBlank(agencyAddress)) {
                Assert.isExcessLength(agencyAddress, 50, "地址内容过长");
            }
            if (oldAgency.getLevel() > 2 ) {// 3小区 和 4水泵房  需要选择经纬度
                if (longitude == null || latitude == null) {
                    return R.error(400, "请定位经纬度");
                }
            }
            boolean isEditName = false;
            if (!name.equals(oldAgency.getName())) {// 判断是否修改名称
                isEditName = true;
                if(oldAgency.getLevel()==4){// 4水泵房  名称同层级唯一
                    if (orgService.selectCount(new EntityWrapper<IotAgency>().eq("company_code",currentUserMap.get("companyCode")).eq("parent_id",oldAgency.getParentId()).eq("agency_name", name)) > 0) {
                        return R.error(400, "已存在相同名称");
                    }
                }
                if(oldAgency.getLevel()<4){// 2物业，3小区  名称全局唯一
                    if (orgService.selectCount(new EntityWrapper<IotAgency>().eq("company_code",currentUserMap.get("companyCode")).eq("agency_name", name)) > 0) {
                        return R.error(400, "已存在相同名称");
                    }
                }
            }
            if (!code.equals(oldAgency.getCode())) {// 判断是否修改机构编码,全局唯一
                if (orgService.selectCount(new EntityWrapper<IotAgency>().eq("company_code",currentUserMap.get("companyCode")).eq("agency_code", code)) > 0) {
                    return R.error(400, "已存在相同编码");
                }
            }
            IotAgency editAgency = new IotAgency();
            editAgency.setId(id);
            editAgency.setName(name);
            editAgency.setCode(code);
            editAgency.setLinkPhone(linkPhone);
            editAgency.setLinkName(linkName);
            editAgency.setLongitude(longitude);
            editAgency.setLatitude(latitude);
            editAgency.setAgencyAddress(agencyAddress);
            editAgency.setDesc(desc);
            editAgency.setLevel(oldAgency.getLevel());
            // 设置修改人
            editAgency.setUpdateTime(new Date());
            editAgency.setUpdateBy(currentUserInfo.getId());
            orgService.updateById(editAgency,isEditName);// updateById 只会 修改值不为空的属性字段
        }
        return R.ok();
    }

    /*
     * 查看信息
     * @param
     * @return
     */
    @ApiOperation(value = "查看信息")
    @RequestMapping(value = "/read",method ={ RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name="id",value="id",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="level",value="级别(2-物业/公司,3-小区,4-水泵房,5-水泵组)",required = true,dataType = "int",paramType="form"),
    })
    public R read(Long id,Integer level){
        Assert.isNull(id,"参数id不能为空");
        Assert.isNull(level,"参数level不能为空");
        if(level>4){
            IotWaterPumpGroup oldWaterPumpGroup = waterPumpGroupService.selectById(id);
            Assert.isNull(oldWaterPumpGroup,"未查询到水泵组信息");
            return R.ok().put("data",oldWaterPumpGroup);
        }
        IotAgency agency = orgService.selectById(id);
        Assert.isNull(agency,"未查询到相关信息");
        return R.ok().put("data",agency);
    }

    /*
    * 分页查看分区信息
    * @param
    * @return
    */
    @ApiOperation(value = "分页查看机构信息")
    @RequestMapping(value = "/page",method ={ RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name="parentId",value="列表机构id",required = false,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="searchValue",value="搜索框内容",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="pageSize",value="分页查询条数",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="pageNum",value="分页查询页数",required = false,dataType = "int",paramType="form"),
    })
    public R page(String searchValue,Integer pageSize,Integer pageNum,Long parentId){
//        Map<String,String> currentUserMap = getCurrentUserMap();
//        UserInfo currentUserInfo=systemRpcService.getUserByUsername(currentUserMap.get("userName"),currentUserMap.get("companyCode"));
//        Assert.isNull(currentUserInfo.getGroupType(),"请重新登录");
        Integer roleType =null;
        Long roleId =null;
        String companyCode =null;
        try {
            roleType = getCurrentRoleType();
            roleId = getCurrentRoleId();
            companyCode = getCurrentCompanyCode();
        }catch (NumberFormatException ex){
            return  R.error(400,"请重新登录");
        }
        if(roleId==null||roleType==null||companyCode==null){
            return  R.error(400,"请重新登录");
        }
        if(parentId==null){parentId=-1L;}// 默认查询系统
        if(pageNum==null||pageNum < 1){pageNum=1;}
        if(pageSize==null||pageSize < 1){pageSize=10;}
        Page<Map<String,Object>> pages = new Page<Map<String,Object>>(pageNum,pageSize);
        Wrapper<Map<String,Object>> wr = new EntityWrapper<Map<String,Object>>();
        wr.eq("t1.companyCode",companyCode);
        if(StringUtils.isNotBlank(searchValue)){// 根据搜索框内容 全展示字段搜索
            StringBuilder likeWhere = new StringBuilder(160);
            likeWhere.append("( t1.name LIKE '%"+searchValue+"%')");
            likeWhere.append(" or ( t1.code LIKE '%"+searchValue+"%')");
            likeWhere.append(" or ( t1.linkPhone LIKE '%"+searchValue+"%')");
            likeWhere.append(" or ( t1.linkName LIKE '%"+searchValue+"%')");
            likeWhere.append(" or ( t1.agencyAddress LIKE '%"+searchValue+"%')");
            wr.andNew(likeWhere.toString());
        }
        Map<String,String> map =new HashMap<String,String>();
        if(1==roleType){// 默认角色类型,所有机构权限
            if(parentId.longValue() != -1L){// 根据 左侧分区列表的当前分区下旬下级所有分区。
                List<Long> orgIds = orgService.getSubordinateAgencyIds(parentId);//获取所有机构id
                if(orgIds==null){orgIds = new ArrayList<Long>();}
                StringBuffer orgIdsStr = new StringBuffer("");
                orgIdsStr.append(parentId);
                for(int x=0,length =orgIds.size();x<length;x++ ){
                    orgIdsStr.append(",").append(orgIds.get(x));
                }
                map.put("orgIds",orgIdsStr.toString());
                String groupIdsStr = waterPumpGroupService.getGroupIdsStrByHouseId(map.get("orgIds"));
                if(groupIdsStr==null){
                    groupIdsStr =parentId+"";
                }else{
                    groupIdsStr=parentId+","+groupIdsStr;
                }
                map.put("groupIds",groupIdsStr);
            }
        }
        if(1!=roleType){//自定义角色类型
            // 获取角色 拥有的 机构id权限
            String agencyIdsStr =groupIotAgencyService.getAgencyIdsStrByGroupId(roleId+"");
            Assert.parameterIsBlank(agencyIdsStr,"您暂无机构权限，请联系管理员");
            if(parentId.longValue() != -1L){// 根据 左侧分区列表的当前分区下旬下级所有分区。
                List<Long> orgIds = orgService.getSubordinateAgencyIds(parentId);//获取所有机构id
                if(orgIds==null){orgIds = new ArrayList<Long>();}
                StringBuffer orgIdsStr = new StringBuffer("");
                if (agencyIdsStr.indexOf( parentId +"" )!=-1) {
                    orgIdsStr.append(parentId);
                }
                if(orgIdsStr.length()<1){
                    orgIdsStr.append("-1");
                }
                for(int x=0,length =orgIds.size();x<length;x++ ){
                    if (agencyIdsStr.indexOf( orgIds.get(x)+"" ) != -1){
                        orgIdsStr.append(",").append(orgIds.get(x));
                    }
                }
                map.put("orgIds",orgIdsStr.toString());
            }else{
                map.put("orgIds",agencyIdsStr);
            }
            String groupIdsStr = waterPumpGroupService.getGroupIdsStrByHouseId(map.get("orgIds"));
            if(groupIdsStr==null){
                groupIdsStr =parentId+"";
            }else{
                groupIdsStr=parentId+","+groupIdsStr;
            }
            map.put("groupIds",groupIdsStr);
        }
        pages = orgService.selectPage(pages,wr,map);
        return R.ok().put("data",pages);
    }
    /*
    * 查看机构信息集合
    * @param
    * @return
    */
    @ApiOperation(value = "查看机构信息列表")
    @RequestMapping(value = "/list",method ={ RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name="level",value="查询类型(2-物业/公司(默认),3-小区,4-水泵房,5-水泵组)",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="parentId",value="上级id",required = false,dataType = "Long",paramType="form"),
    })
    public R list(Integer level,Long parentId){
        if(level==null||level<1||level>5){ level = 2;}// 默认查询  物业
        List<Map<String,Object>> returnList = null;
        // 获取当前用户角色
//        Map<String,String> currentUserMap=getCurrentUserMap();
//        UserInfo currentUserInfo=systemRpcService.getUserByUsername(currentUserMap.get("userName"),currentUserMap.get("companyCode"));
//        Assert.isNull(currentUserInfo.getGroupType(),"请重新登录");
        // 获取当前角色 拥有的 机构id权限
        String agencyIdsStr = null;
        Integer roleType =null;
        Long roleId =null;
        String companyCode =null;
        try {
            roleType = getCurrentRoleType();
            roleId = getCurrentRoleId();
            companyCode = getCurrentCompanyCode();
        }catch (NumberFormatException ex){
            return  R.error(400,"请重新登录");
        }
        if(roleId==null||roleType==null||companyCode==null){
            return  R.error(400,"请重新登录");
        }
        if(1!=roleType){// 自定义角色
            agencyIdsStr =groupIotAgencyService.getAgencyIdsStrByGroupId(roleId+"");
            Assert.parameterIsBlank(agencyIdsStr,"您暂无机构权限，请联系管理员");
        }
        if(level==5){//查询水泵组
            Wrapper<IotWaterPumpGroup> WP = new EntityWrapper<IotWaterPumpGroup>();
            WP.eq("company_code",companyCode);
            if(null!=agencyIdsStr) {// 自定义角色 根据当前角色 拥有 权限 过滤
                WP.in("house_id", agencyIdsStr);
            }
            if(parentId!=null && parentId.longValue()!=-1L){
                WP.eq("house_id",parentId);
            }
            returnList =waterPumpGroupService.selectMapList(WP);
        }
        if(level<5){// 查询 物业,小区,水泵房
            Wrapper<IotAgency> WP = new EntityWrapper<IotAgency>();
            WP.eq("company_code",companyCode);
            WP.eq("agency_level",level);
            if(null!=agencyIdsStr) {
                WP.in("agency_id", agencyIdsStr);//自定义角色 根据当前角色 拥有 权限 过滤
            }
            if(parentId!=null&& parentId.longValue()!=-1L){
                WP.eq("parent_id",parentId);
            }
            returnList =orgService.selectMapList(WP);
        }
        if(returnList==null){returnList=new ArrayList<Map<String,Object>>();}
        return R.ok().put("data",returnList);
    }
    /*
     * 查询分区树结构
     * @param
     * @return
     */
    @ApiOperation(value = "查询机构树结构")
    @RequestMapping(value = "/readAgencyTree",method ={ RequestMethod.POST})
    @ApiImplicitParams({
        @ApiImplicitParam(name="companyCode",value="用户公司编码",required = true,dataType = "int",paramType="form"),
        @ApiImplicitParam(name="readTreeLevel",value="查询树结构层级(1-系统,2-物业/公司,3-小区,4-水泵房,5-水泵组)",required = false,dataType = "int",paramType="form"),
        @ApiImplicitParam(name="checked",value="是否默认全部选中(0-未选中(默认),1-选中)",required = false,dataType = "int",paramType="form"),
        @ApiImplicitParam(name="opened",value="是否默认全部展开(0-未展开(默认),1-展开)",required = false,dataType = "int",paramType="form"),
    })
    public R readAgencyTree(Integer readTreeLevel,Integer checked,Integer opened,String companyCode){
        if(readTreeLevel==null||readTreeLevel<1){readTreeLevel = 5;}// 默认查询5级
        if(opened==null||opened!=1){opened=0;}
        if(checked==null||checked!=1){checked=0;}
        Map<String,Object> returnMap = new HashMap<String,Object>();
        returnMap.put("id",-1L);
        returnMap.put("name","系统");
        returnMap.put("code","system");
        returnMap.put("parentId",-2);
        returnMap.put("level",1);
        returnMap.put("checked",checked);
        returnMap.put("opened",opened);
        if(readTreeLevel==1){
            returnMap.put("children",new ArrayList< Map<String,Object>>());
            return R.ok().put("data",returnMap);
        }
        Wrapper<IotAgency> agencyWp = new EntityWrapper<IotAgency>();
        agencyWp.eq("company_code",companyCode);
//        agencyWp.eq("status",1);
        if(readTreeLevel<4){
            agencyWp.le("agency_level",readTreeLevel);//  判断 机构等级  <=
        }
        List<Map<String,Object>> treeList = orgService.selectMapList(agencyWp);
        if(readTreeLevel>4){//查询到水泵组
            Wrapper<IotWaterPumpGroup> waterPumpGroupWp = new EntityWrapper<IotWaterPumpGroup>();
            waterPumpGroupWp.eq("company_code",companyCode);
//            List<Map<String,Object>> waterPumpGroupList = waterPumpGroupService.selectMapList(waterPumpGroupWp);
            treeList.addAll( waterPumpGroupService.selectMapList(waterPumpGroupWp) );
        }
        List<Map<String,Object>> treeChildrenList = orgService.agencyFactorTree(treeList,checked,opened);
        returnMap.put("children",treeChildrenList);
        return R.ok().put("data",returnMap);
    }

    /*
        * 查看信息
        * @param
        * @return
        */
    @ApiOperation(value = "删除信息")
    @RequestMapping(value = "/del",method ={ RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name="id",value="id",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="level",value="级别(2-物业/公司,3-小区,4-水泵房,5-水泵组)",required = true,dataType = "int",paramType="form"),
    })
    public R del(Long id,Integer level){
        Assert.isNull(id,"参数id不能为空");
        Assert.isNull(level,"参数level不能为空");
//        if(level==2){
//            return R.error(400,"物业机构不能删除");
//        }
        if(level<2||level>5){
            return R.error(400,"参数level有误");
        }
        Map<String,String> currentUserMap = getCurrentUserMap();
        Map<String,Boolean> valueMap = getWayRpcService.validateUserToken(currentUserMap);
        if(!valueMap.get("value")){
            return R.error(400,"Token失效,请重新登录");
        }
        try {
            orgService.joinDelete(id, level);
        }catch (RRException ex){
            throw ex;
        }
//        if(level>4){// 只删除 水泵组
//            waterPumpGroupService.deleteById(id);// 直接删除水泵组
//            return R.ok();
//        }
//        List<Long> orgIds = orgService.getSubordinateAgencyIds(id);//获取所有机构id
//        if(orgIds==null){orgIds = new ArrayList<Long>();}
//        StringBuffer orgIdsStr = new StringBuffer("");
//        orgIdsStr.append(id);
//        for(int x=0,length =orgIds.size();x<length;x++ ){
//            orgIdsStr.append(",").append(orgIds.get(x));
//        }
//        orgService.delAgencyAndWaterPumpGroup(orgIdsStr.toString());
        return R.ok();
    }

    /*
        * 查询分区树结构
        * @param
        * @return
        */
    @ApiOperation(value = "查询机构树结构 通过登录用户")
    @RequestMapping(value = "/readAgencyTreeByUser",method =RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="readTreeLevel",value="查询树结构层级(1-系统,2-物业/公司,3-小区,4-水泵房,5-水泵组)",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="checked",value="是否默认全部选中(0-未选中(默认),1-选中)",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="opened",value="是否默认全部展开(0-未展开(默认),1-展开)",required = false,dataType = "int",paramType="form"),
    })
    public R readAgencyTreeByUser(Integer readTreeLevel,Integer checked,Integer opened){
        if(readTreeLevel==null||readTreeLevel<1){readTreeLevel = 5;}// 默认查询5级
        if(opened==null||opened!=1){opened=0;}
        if(checked==null||checked!=1){checked=0;}
        Map<String,Object> returnMap = new HashMap<String,Object>();
        returnMap.put("id",-1L);
        returnMap.put("name","系统");
        returnMap.put("code","system");
        returnMap.put("parentId",-2);
        returnMap.put("level",1);
        returnMap.put("checked",checked);
        returnMap.put("opened",opened);
        if(readTreeLevel==1){
            returnMap.put("children",new ArrayList< Map<String,Object>>());
            return R.ok().put("data",returnMap);
        }
//        Map<String,String> currentUserMap = getCurrentUserMap();
        // 获取当前用户角色
//        UserInfo currentUserInfo=systemRpcService.getUserByUsername(currentUserMap.get("userName"),currentUserMap.get("companyCode"));
//        Assert.isNull(currentUserInfo.getGroupType(),"请重新登录");
        // 获取当前角色 拥有的 机构id权限
        String agencyIdsStr = null;
        Integer roleType =null;
        Long roleId =null;
        String companyCode =null;
        try {
            roleType = getCurrentRoleType();
            roleId = getCurrentRoleId();
            companyCode = getCurrentCompanyCode();
        }catch (NumberFormatException ex){
            return  R.error(400,"请重新登录");
        }
        if(roleId==null||roleType==null||companyCode==null){
            return  R.error(400,"请重新登录");
        }
        if(roleType!=1) {
            agencyIdsStr = groupIotAgencyService.getAgencyIdsStrByGroupId( roleId+ "");
            Assert.parameterIsBlank(agencyIdsStr,"您暂无机构权限，请联系管理员");
        }
        Wrapper<IotAgency> agencyWp = new EntityWrapper<IotAgency>();
        agencyWp.eq("company_code",companyCode);
//        agencyWp.eq("status",1);
        if(agencyIdsStr!=null){
            agencyWp.in("agency_id",agencyIdsStr);
        }
        if(readTreeLevel<4){
            agencyWp.le("agency_level",readTreeLevel);//  判断 机构等级  <=
        }
        List<Map<String,Object>> treeList = orgService.selectMapList(agencyWp);
        if(readTreeLevel>4){//查询到水泵组
            Wrapper<IotWaterPumpGroup> waterPumpGroupWp = new EntityWrapper<IotWaterPumpGroup>();
            waterPumpGroupWp.eq("company_code",companyCode);
            if(agencyIdsStr!=null){
                waterPumpGroupWp.in("house_id",agencyIdsStr);
            }
//          List<Map<String,Object>> waterPumpGroupList = waterPumpGroupService.selectMapList(waterPumpGroupWp);
            treeList.addAll( waterPumpGroupService.selectMapList(waterPumpGroupWp) );
        }
        List<Map<String,Object>> treeChildrenList = orgService.agencyFactorTree(treeList,checked,opened);
        returnMap.put("children",treeChildrenList);
        return R.ok().put("data",returnMap);
    }
}
